package com.csi.controller.user;

import com.alibaba.fastjson2.JSON;
import com.cloopen.rest.sdk.BodyType;
import com.cloopen.rest.sdk.CCPRestSmsSDK;
import com.csi.pojo.Result;
import com.csi.service.UserService;
import com.csi.service.impl.UserServiceImpl;
import redis.clients.jedis.Jedis;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Random;
import java.util.Set;

@WebServlet("/user/sendMessageController")
public class SendMessageController extends HttpServlet {

    // 生产环境请求地址：app.cloopen.com
    String serverIp = "app.cloopen.com";

    // 请求端口
    String serverPort = "8883";

    // 主端口，控制台开发者主账户ACCOUNT SID和主账号令牌AUTH TOKEN
    String accountSID = "2c94811c8a27cf2d018a4a3afd930d85";
    String accountToken = "9000558bca8a46888838884f7f66772f";
    String appId = "2c94811c8a27cf2d018a4a3afeee0d8c";

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        resp.setContentType("application/json;charset=utf-8");
        Result result = new Result<>();
        UserService userService = new UserServiceImpl();

        // 发送验证码到指定手机
        String phone = req.getParameter("phone");

        // 判断该手机号是否注册，如果没有注册，则不能获取到验证码
        if (userService.findUserByPhone(phone) == null) {
            result.setCode(7001);
            result.setMsg("该手机号未注册");
        } else {
            // 4位验证码
            Random random = new Random();

            StringBuffer code = new StringBuffer();

            for (int i = 0; i < 4; i++){
                int num = random.nextInt(10);

                // 第一位数不能为0
                while (num == 0 && i == 0){
                    num = random.nextInt(10);
                }
                code.append(num);
            }

            String codeStr = code.toString();

            CCPRestSmsSDK sdk = new CCPRestSmsSDK();
            sdk.init(serverIp, serverPort);
            sdk.setAccount(accountSID,accountToken);
            sdk.setAppId(appId);
            sdk.setBodyType(BodyType.Type_JSON);

            // 短信模板id 默认测试环境的id是1
            String templateId = "1";
            // 占位符传值，参数1：4位验证码， 参数2：验证码有效时长
            String[] datas = {codeStr,"1"};

            HashMap<String,Object> sdkResult = sdk.sendTemplateSMS(phone,templateId,datas);

            if ("000000".equals(sdkResult.get("statusCode"))){
                // 正常返回输入data包体信息（map）

                HashMap<String,Object> data = (HashMap<String, Object>) sdkResult.get("data");
                Set<String> keySet = data.keySet();
                for (String key1:keySet){
                    Object object = data.get(key1);
                    System.out.println(key1 + " = " + object);
                }

                // 将验证码存储到 session 中
                // HttpSession session = req.getSession();
                // session.setMaxInactiveInterval(60);
                // session.setAttribute(phone, codeStr);

                // 将验证码存储到 application 中
                ServletContext application = req.getServletContext();
                // 设置过期时间为1分钟
                long expireTime = System.currentTimeMillis() + 60 * 1000;
                application.setAttribute(phone, new VerifyCode(codeStr, expireTime));

                result.setCode(200);
                result.setMsg("success");
                result.setDatas(codeStr);
            }else {
                // 异常返回输入错误码和错误信息
                result.setCode(400);
                result.setMsg("false");
            }
        }

        PrintWriter out = resp.getWriter();
        out.print(JSON.toJSONString(result));
        out.flush();
        out.close();
    }
}

